package com.example.wyc.mybiye1;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyc.mybiye.R;
import com.example.wyc.mybiye1.lei.guangMingLei;
import com.example.wyc.mybiye1.sql.MYSQL;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import WZ_Link.WZ_Link_Inter;

public class Ma4Activity implements WZ_Link_Inter.onGetData{
    Activity mContext;
    Context context_t;
    private LayoutInflater mInflater;
    private View mCurrentView;
    //----
    WZ_Link_Inter sdkManager;
    //--
    private AssetManager aManager;
    private SoundPool mSoundPool = null;
    private HashMap<Integer, Integer> soundID = new HashMap<Integer, Integer>();

    public MYSQL mysql;
    //--
    public Ma4Activity(Activity context, Context context_t){
        this.mContext=context;
        this.context_t=context_t;
        //为之后将Layout转化为view时用
        mInflater = LayoutInflater.from(mContext);
    }
    public TextView guangMing,wenDu,shiDu,qiTi,hongWai,RFID,yuDi,fengShan,dianZhen,RGB,yuYin,ipText;
    public Button souSuo,dengLu,jieShou,tiaoZhuan,qingKong,chaXunJiLu;
    public void initView(){
        //设置布局文件
        mCurrentView = mInflater.inflate(R.layout.activity_ma4, null);
        sdkManager = new WZ_Link_Inter("WZZCKJYXGS");
        //sdkManager.setSdkDataListener(this);
        mysql=new MYSQL(context_t);
        guangMing=mCurrentView.findViewById(R.id.guangMing);
        wenDu=mCurrentView.findViewById(R.id.wenDu);
        shiDu=mCurrentView.findViewById(R.id.shiDu);
        qiTi=mCurrentView.findViewById(R.id.qiTi);

        hongWai=mCurrentView.findViewById(R.id.hongWai);
        RFID=mCurrentView.findViewById(R.id.RFID);
        yuDi=mCurrentView.findViewById(R.id.yuDi);

        fengShan=mCurrentView.findViewById(R.id.fengShan);
        dianZhen=mCurrentView.findViewById(R.id.dianZhen);
        RGB=mCurrentView.findViewById(R.id.RGB);
        yuYin=mCurrentView.findViewById(R.id.yuYin);
        ipText=mCurrentView.findViewById(R.id.ipText);

        souSuo=mCurrentView.findViewById(R.id.souSuo);
        dengLu=mCurrentView.findViewById(R.id.dengLu);
        dengLu.setEnabled(false);
        jieShou=mCurrentView.findViewById(R.id.jieShou);
        jieShou.setEnabled(false);

        qingKong=mCurrentView.findViewById(R.id.qingKong);
        builder = new AlertDialog.Builder(context_t);

        tiaoZhuan=mCurrentView.findViewById(R.id.tiaoZhuan);
        chaXunJiLu=mCurrentView.findViewById(R.id.chaXunJiLu);
        //--
        aManager=context_t.getAssets();
        try {
            initSP();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //--
        jianTing();
        threadSql.start();
    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    Toast.makeText(context_t, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Map<String, String> map = (Map<String, String>) msg.obj;
                    show(map);
                    break;
                case 2:
                    sdkManager.attentionVariableByUIID("30008");
                    yanChi(500);
                    //guangMing.setBackground(context_t.getDrawable(R.mipmap.wyc_guangming_1));
                    sdkManager.attentionVariableByUIID("30009");
                    yanChi(500);
                    //wenDu.setBackground(context_t.getDrawable(R.mipmap.wyc_wendu_1));
                    sdkManager.attentionVariableByUIID("30010");
                    yanChi(500);
                    //shiDu.setBackground(context_t.getDrawable(R.mipmap.wyc_shidu_1));
                    sdkManager.attentionVariableByUIID("30011");
                    yanChi(500);
                    //qiTi.setBackground(context_t.getDrawable(R.mipmap.wyc_qiti_1));
                    sdkManager.attentionVariableByUIID("30013");
                    yanChi(500);
                    //hongWai.setBackground(context_t.getDrawable(R.mipmap.wyc_hongwai_1));
                    sdkManager.attentionVariableByUIID("30022");
                    yanChi(500);
                    break;
                case 3://温度
                    //wenDu.setBackground(context_t.getDrawable(R.mipmap.wyc_wendu_1));
                    wenDu.setSelected(true);
                    wenDu.setText("温度："+msg.obj.toString());
                    GM=msg.obj.toString();
                    is_threadSql=true;
                    break;
                case 4://湿度
                    //shiDu.setBackground(context_t.getDrawable(R.mipmap.wyc_shidu_1));
                    shiDu.setSelected(true);
                    shiDu.setText("湿度："+msg.obj.toString());
                    break;
                case 5://光敏
                    //guangMing.setBackground(context_t.getDrawable(R.mipmap.wyc_guangming_1));
                    guangMing.setSelected(true);
                    guangMing.setText("光照："+msg.obj.toString());
                    break;
                case 6://可燃气体
                    //qiTi.setBackground(context_t.getDrawable(R.mipmap.wyc_qiti_1));
                    qiTi.setSelected(true);
                    qiTi.setText("可燃气体："+msg.obj.toString());
                    break;
                case 7://人体红外
                    //hongWai.setBackground(context_t.getDrawable(R.mipmap.wyc_hongwai_1));
                    hongWai.setSelected(true);
                    hongWai.setText("人体红外："+msg.obj.toString());
                    break;
                case 8://RFID
                    //RFID.setBackground(context_t.getDrawable(R.mipmap.wyc_rfid_2));
                    RFID.setSelected(true);
                    RFID.setText("RFID："+msg.obj.toString());
                    break;
                case 9://雨滴检测
                    //yuDi.setBackground(context_t.getDrawable(R.mipmap.wyc_yudi_1));
                    yuDi.setSelected(true);
                    yuDi.setText("雨滴检测："+msg.obj.toString());
                    break;
                case 10://风扇操作
                    mSoundPool.play(soundID.get(2), 1, 1, 0, 0, 1);
                    if ((Integer) msg.obj==0){
                        fengShan.setSelected(true);
                        fengShan.setText("风扇：关");
                    }else if ((Integer) msg.obj==1){
                        fengShan.setSelected(false);
                        fengShan.setText("风扇：开");
                    }
                    yanChi(200);
                    sdkManager.ControlDev("30016","1", (Integer) msg.obj);
                    break;
                case 11://点阵
                    mSoundPool.play(soundID.get(1), 1, 1, 0, 0, 1);
                    if ((Integer) msg.obj==0){
                        dianZhen.setSelected(false);
                    }else {
                        dianZhen.setSelected(true);
                    }
                    dianZhen.setText("点阵："+msg.obj);
                    sdkManager.ControlDev("30021","1",(Integer) msg.obj);
                    yanChi(200);
                    break;
                case 12://RGB
                    mSoundPool.play(soundID.get(2), 1, 1, 0, 0, 1);
                    if ((Integer) msg.obj==0){
                        RGB.setSelected(false);
                    }else {
                        RGB.setSelected(true);
                    }
                    RGB.setText("RGB："+msg.obj);
                    sdkManager.ControlDev("30018","1",(Integer) msg.obj);
                    yanChi(200);
                    break;
                case 13://语音
                    mSoundPool.play(soundID.get(1), 1, 1, 0, 0, 1);
                    if ((Integer) msg.obj==0){
                        yuYin.setSelected(false);
                    }else {
                        yuYin.setSelected(true);
                    }
                    yuYin.setText("语音："+msg.obj);
                    sdkManager.ControlDev("30023","1",(Integer) msg.obj);
                    yanChi(200);

                    break;
            }
        }
    };
    ProgressDialog progressDialog;
    String sn;
    String ip;
    List<String> iplist = new ArrayList<>();
    List<String> hostlist = new ArrayList<>();
    AlertDialog.Builder builder;
    AlertDialog alertDialog;

    //自己的选择
    private AlertDialog alert2 = null;
    private AlertDialog.Builder builder2 = null;
    public void jianTing(){
        souSuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressDialog = new ProgressDialog(context_t);
                progressDialog.setMessage("搜索中...");
                progressDialog.show();
                new Thread() {
                    public void run() {
                        SearchGateWay();
                    }
                }.start();
            }
        });

        dengLu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSoundPool.play(soundID.get(2), 1, 1, 0, 0, 1);
                sdkManager.Login_host(ip, sn);
                jieShou.setEnabled(true);
            }
        });

        jieShou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSoundPool.play(soundID.get(2), 1, 1, 0, 0, 1);
                Message msg=new Message();
                msg.what=2;
                handler.sendMessage(msg);
            }
        });

        fengShan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String[] lesson = new String[]{"0", "1"};
                alert2 = null;
                builder2 = new AlertDialog.Builder(mContext);
                alert2 = builder2 .setTitle("风扇操作？").setItems(lesson, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Toast.makeText(context_t, "你选择了" + lesson[i], Toast.LENGTH_SHORT).show();

                            Message msg=new Message();
                            msg.what=10;
                            msg.obj=i;
                            handler.sendMessage(msg);

                    }
                }).create();
                alert2.show();
            }
        });
        dianZhen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String[] lesson = new String[]{"0", "1","2","3","4","5","6"};
                alert2 = null;
                builder2 = new AlertDialog.Builder(mContext);
                alert2 = builder2 .setTitle("点阵操作？").setItems(lesson, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Toast.makeText(context_t, "你选择了" + lesson[i], Toast.LENGTH_SHORT).show();
                        Message msg=new Message();
                        msg.what=11;
                        msg.obj=i;
                        handler.sendMessage(msg);
                    }
                }).create();
                alert2.show();
            }
        });
        RGB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String[] lesson = new String[]{"0", "1","2","3","4","5","6"};
                alert2 = null;
                builder2 = new AlertDialog.Builder(mContext);
                alert2 = builder2 .setTitle("RGB操作？").setItems(lesson, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Toast.makeText(context_t, "你选择了" + lesson[i], Toast.LENGTH_SHORT).show();

                        Message msg=new Message();
                        msg.what=12;
                        msg.obj=i;
                        handler.sendMessage(msg);

                    }
                }).create();
                alert2.show();
            }
        });

        yuYin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String[] lesson = new String[]{"0", "1","2","3","4","5","6"};
                alert2 = null;
                builder2 = new AlertDialog.Builder(mContext);
                alert2 = builder2 .setTitle("语音播报？").setItems(lesson, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Toast.makeText(context_t, "你选择了" + lesson[i], Toast.LENGTH_SHORT).show();

                        Message msg=new Message();
                        msg.what=13;
                        msg.obj=i;
                        handler.sendMessage(msg);

                    }
                }).create();
                alert2.show();
            }
        });

        tiaoZhuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(context_t,CanvasActivity.class);
                context_t.startActivity(intent);
//                guangMingLei gmlei= mysql.chaXunGuangMing2();
//                String str=gmlei.Gms.get(0)+gmlei.Gms.get(1);
//                Toast.makeText(context_t, str, Toast.LENGTH_SHORT).show();
            }
        });

        qingKong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mysql.shanChu();
            }
        });

        chaXunJiLu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mysql.chaXunGuangMing();
            }
        });
    }
    //是否连接WIFI
    public boolean isWifiConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context_t.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetworkInfo.isConnected()) {
            return true;
        }
        return false;
    }
    //搜索
    public void SearchGateWay() {
        if (!isWifiConnected()) {
            senToast("请先连接物联网关所在路由WIFI");
            return;
        }

        sdkManager.initSearch(getHostIP());
        sdkManager.setSdkDataListener(this);
    }
    /**
     * 获取ip地址
     *
     * @return
     */


    public  String getHostIP() {
        //获取wifi服务
        WifiManager wifiManager = (WifiManager) context_t.getSystemService(Context.WIFI_SERVICE);
        //判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ip = intToIp(ipAddress);
        return ip;
    }
    private  String intToIp(int i) {

        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

    private void show(Map<String, String> map) {
        progressDialog.dismiss();
        Set<String> s = map.keySet();
        for (String key : s) {
            // 根据得到的键，获取对应的值
            iplist.add(key);
            hostlist.add(map.get(key));
        }
        ListView listView = new ListView(context_t);
        listView.setAdapter(new ArrayAdapter<String>(context_t, android.R.layout.simple_list_item_1, iplist));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                alertDialog.dismiss();
                ipText.setText(iplist.get(i));
                sn = hostlist.get(i);
                ip = iplist.get(i);
                dengLu.setEnabled(true);
            }
        });
        builder.setView(listView);
        alertDialog = builder.show();
    }


    //发送消息
    public void senToast(String str) {
        Message msg = new Message();
        msg.what = 0;
        msg.obj = str;
        handler.sendMessage(msg);
    }
    //延迟
    public void yanChi(int i){
        try {
            Thread.sleep(i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前在导航栏上方显示对应的View
     */
    public View getView() {
        if (mCurrentView == null) {
            initView();
        }
        return mCurrentView;
    }
    /**
     * 显示当前导航栏上方所对应的view界面
     */
    public void showView(){
        if(mCurrentView == null){
            initView();
        }
        mCurrentView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onSearchFinish(Map<String, String> map) {
        Message message = new Message();
        message.what = 1;
        message.obj = map;
        handler.sendMessage(message);
    }

    @Override
    public void getLandState(boolean b, String s) {
        if (b) {
            senToast("登录成功");
        }else{
            senToast("登录失败");
        }
    }

    @Override
    public void getDevData(String s, String s1, String s2, String s3, String s4, String s5) {
        if (s.equals("30008")){
                if (s3.equals("1")){
                    Message msg=new Message();
                    msg.what=3;
                    msg.obj=s1;
                    handler.sendMessage(msg);
                }else if (s3.equals("2")){
                    Message msg=new Message();
                    msg.what=4;
                    msg.obj=s1;
                    handler.sendMessage(msg);
                }
        }

        if (s.equals("30009")){
            Message msg=new Message();
            msg.what=5;
            msg.obj=s1;
            handler.sendMessage(msg);
        }

        if (s.equals("30010")){
            Message msg=new Message();
            msg.what=6;
            msg.obj=s1;
            handler.sendMessage(msg);
        }

        if (s.equals("30011")){
            Message msg=new Message();
            msg.what=7;
            msg.obj=s1;
            handler.sendMessage(msg);
        }


        if (s.equals("30013")){
            if (!s2.equals("") || !s2.equals(null)) {
                Message msg = new Message();
                msg.what = 8;
                msg.obj = s2;
                handler.sendMessage(msg);
            }
        }

        if (s.equals("30022")){
            Message msg=new Message();
            msg.what=9;
            msg.obj=s1;
            handler.sendMessage(msg);
        }
    }

    @Override
    public void getSetVarState(String s, String s1, String s2) {

    }

    @Override
    public void getSetKeyState(String s, String s1, String s2) {

    }

    //音效
    private void initSP() throws Exception{
        //设置最多可容纳5个音频流，音频的品质为5
        mSoundPool = new SoundPool(5, AudioManager.STREAM_SYSTEM, 5);
        soundID.put(1, mSoundPool.load(context_t, R.raw.duang, 1));
        soundID.put(2 , mSoundPool.load(context_t.getAssets().openFd("biaobiao.mp3") , 1));  //需要捕获IO异常
        soundID.put(3, mSoundPool.load(context_t, R.raw.duang, 1));
        soundID.put(4, mSoundPool.load(context_t, R.raw.duang, 1));
        soundID.put(5, mSoundPool.load(context_t, R.raw.duang, 1));
        soundID.put(6 , mSoundPool.load(context_t.getAssets().openFd("biaobiao.mp3") , 1));  //需要捕获IO异常
        soundID.put(7 , mSoundPool.load(context_t.getAssets().openFd("biaobiao.mp3") , 1));  //需要捕获IO异常
    }

    //保存数据库
    boolean is_threadSql=false;
    String GM;
    Thread threadSql=new Thread(){
        @Override
        public void run() {
            while (true) {
                if (is_threadSql) {
                    try {
                        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH/mm");
                        String time= simpleDateFormat.format(new Date());
                        mysql.baoCunGuangMin(GM,time);
                        Thread.sleep(60000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };
}
